#include "UdpClient.hpp"
#include "Common.hpp"

int main(int argc, char* argv[])  // 应该传入服务器名、ip和端口号
{
    if(argc != 3)
    {
        cerr << "Usage: " << argv[0] << " serverip serverport" << endl;
        Die(USAGE_ERR);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    // 1. 创建socket
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cerr << "socket error" << endl;
        Die(SOCKET_ERR);
    }

    // 填充server信息   
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));  // bzero 函数可以将指定数据清零
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);  // 端口号是要被发送给对方的，即发送到网络中的
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    // 客户端一直向服务器发消息
    while(true)
    {
        cout << "Please Enter# ";
        string message;
        getline(cin, message);

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        (void)n;

        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        n = ::recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, CONV(&temp), &len);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
    }
}